package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.*;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: xrl
 * @Date: 2022/10/13  18:10
 * @Version 1.0
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    /**
     * 按条件查询文章列表
     */
    @Override
    public ResponseResult getAll(WmNewsPageReqDto dto) {
        //检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //分页参数校验
        dto.checkParam();
        //分页条件查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //状态精确查询
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //频道精确查询
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //关键字模糊查询
        if (dto.getKeyword() != null) {
            wrapper.eq(WmNews::getTitle, dto.getKeyword());
        }
        //查询当前登录用户的文章
        wrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        //发布时间倒序排序
        wrapper.orderByDesc(WmNews::getCreatedTime);

        //调用方法查询
        page = page(page, wrapper);
        //结果返回
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());

        return result;
    }


    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 提交，修改，保存草稿
     */
    @Override
    @Transactional
    public ResponseResult submitNews(WmNewsDto dto) {
        //1. 数据校验
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2. 保存或者更新文章的数据
        WmNews wmNews = saveOrUpdateNews(dto);

        //3. 判断文章提交是直接提交还是保存草稿   如果状态为0,则保存为草稿,结束当前方法
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //4. 从内容中提取图片
        List<String> materials = ectractUrlInfo(dto.getContent());

        //5. 批量保存内容中的图片与素材的关系
        saveRelativeInfoForContent(materials, wmNews.getId());

        //6. 保存封面图片与素材的关系 —— 封面如果是自动,则需要按照规则匹配图片,再保存数据关系
        saveRelativeInfoForCover(dto, wmNews, materials);

        //7. 调用审核接口,审核文章
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        //添加任务到延迟队列中
        wmNewsTaskService.addWmNewsToTask(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 1.如果文章封面选择自动，则自动匹配封面
     * 匹配规则：
     * 如果内容图片大于等于3  则是多图，截图3张图片作为封面，type = 3
     * 如果内容图片大于等于1 &&小于3  则是单图，截图1张图片作为封面，type = 1
     * 如果内容没有图片，则是无图，type = 0
     * <p>
     * 2.保存封面图片与素材的关系
     */
    /**
     * @param dto
     * @param wmNews
     * @param materials 文章图片集合
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        //封面图片
        List<String> images = dto.getImages();
        //如果文章封面选择自动，则自动匹配封面
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            //封面图片的数量
            int size = materials.size();
            //多图
            if (size >= 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                //截取三张图片，作为封面
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else if (size >= 1 && size < 3) {
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                //截取一张图片作为封面
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }

            //调用方法修改文章
            updateById(wmNews);
        }
        //保存封面图片与素材的关系
        if (images != null && images.size() > 0) {
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    /**
     * 批量保存内容中的图片与素材的关系
     *
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 保存文章图片与素材的关系到数据库中
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        if (materials != null && materials.size() > 0) {
            //根据图片URL获取对应的素材id
            //去重
            materials = materials.stream().distinct().collect(Collectors.toList());
            //构建条件
            LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                    .in(WmMaterial::getUrl, materials);
            //调用方法查询数据库中的素材
            List<WmMaterial> dbWmMaterials = wmMaterialMapper.selectList(wrapper);
            //判断素材是否有效
            if (dbWmMaterials == null || dbWmMaterials.size() == 0 || dbWmMaterials.size() != materials.size()) {
                //素材没找到，或没找够
                //抛出异常，并提示用户，素材引用失效
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            //从数据库素材dbWmMaterials中，取出素材的id
            List<Integer> idList = dbWmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //调用方法批量保存
            wmNewsMaterialMapper.saveRelations(idList, newsId, type);
        }
    }

    /**
     * 从内容中提取图片
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> list = new ArrayList<>();

        //将文章内容转换为map对象
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                //添加到集合
                list.add((String) map.get("value"));
            }
        }
        return list;
    }


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存或者更新文章的数据
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto) {
        WmNews wmNews = new WmNews();
        //拷贝
        BeanUtils.copyProperties(dto, wmNews);

        //图片处理
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            //将封面列表集合转换为字符串
            String imagesStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imagesStr);
        }
        //如果选择自动，值为-1，存储到数据库会报错，暂时修改为null,后面补
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //补充其他数据
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short) 1);//默认上架
        wmNews.setSubmitedTime(new Date());//提交时间

        //新增或者修改文章
        if (dto.getId() == null) {
            //代表是新增操作
            save(wmNews);
        } else {
            //修改文章操作，删除文章图片与素材的关系
            LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, dto.getId());
            //调用方法删除
            wmNewsMaterialMapper.delete(wrapper);
            //修改文章
            updateById(wmNews);
        }
        return wmNews;
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 自媒体文章上下架
     *
     * @param dto
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //检查参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章数据不存在");
        }
        //判断文章是否已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章未发布,不能上下架");
        }
        //修改文章
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
            //代表传递的状态值为 0 或者 1
            LambdaUpdateWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaUpdate()
                    .set(WmNews::getEnable, dto.getEnable())
                    .eq(WmNews::getId, dto.getId());

            //通知article修改文章,进行文章数据同步
            if (wmNews.getArticleId() != null) {
                //封装对象
                Map<String, Object> map = new HashMap<>();
                map.put("articleId", wmNews.getArticleId());
                map.put("enable", dto.getEnable());
                //发送消息
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }
            //调用方法修改文章状态
            update(wrapper);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Autowired
    private WmUserService wmUserService;

    /**
     * 查询文章列表
     */
    @Override
    public ResponseResult news_List(NewsAuthDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        dto.checkParam();
        //分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        //构建条件
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //标题模糊查询
        if (!dto.getTitle().equals("")) {
            wrapper.eq(WmNews::getTitle, dto.getTitle());
        }
        //审核状态匹配
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //调用方法查询
        page = page(page, wrapper);

        //返回结果
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        //设置作者名称
        List<WmNews> records = page.getRecords();
        for (WmNews wmNews : records) {
            Integer user_Id = wmNews.getUserId();
            LambdaQueryWrapper<WmUser> queryWrapper = Wrappers.<WmUser>lambdaQuery().eq(WmUser::getId, user_Id);
            //根据user_id查询作者对象
            WmUser user = wmUserService.getOne(queryWrapper);
            wmNews.setAuthorName(user.getName());
        }

        //为result 设置分页查询数据
        result.setData(records);
        return result;
    }

    /**
     * 查询文章详情
     */
    @Override
    public ResponseResult news_ById(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章
        WmNews wmNews = getById(id);
        //根据user_id查询作者对象
        WmUser wmUser = wmUserService.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getId, wmNews.getUserId()));
        wmNews.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 审核失败
     * 拒绝以后需要给出原因，并修改文章的状态为2
     */
    @Override
    public ResponseResult auth_Fail(NewsAuthDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取文章数据
        WmNews wmNews = getById(dto.getId());
        //失败原因
        wmNews.setReason(dto.getMsg());
        wmNews.setStatus(dto.getStatus());
        //修改
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 审核成功
     * 需要创建app端的文章信息，并更新自媒体文章的状态
     */
    @Override
    @Async  //标明当前方法是一个异步方法
    public ResponseResult auth_Pass(NewsAuthDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取文章数据
        WmNews wmNews = getById(dto.getId());
        wmNews.setStatus(dto.getStatus());
        //修改
        updateById(wmNews);

        //创建app端的文章信息
        saveAppArticle(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private IArticleClient articleClient;

    /**
     * 保存app端相关的文章数据
     *
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDtoBuilder articleDtoBuilder = new ArticleDtoBuilder(wmNews, wmChannelMapper, wmUserMapper);
        //构建dto数据
        ArticleDto dto = articleDtoBuilder
                .buildBeanCopy()
                .buildAuthor()
                .buildChannel()
                .buildBasic()
                .builder();

        //远程调用保存app端文章内容接口
        ResponseResult result = articleClient.saveArticle(dto);
        return result;
    }
}
